package com.wmh.baseservice.operationaid.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wmh.baseservice.common.ex.ServiceException;
import com.wmh.baseservice.common.mybatisplus.structure.LambdaQueryWrapperX;
import com.wmh.baseservice.common.utils.web.UserUtil;
import com.wmh.baseservice.operationaid.convert.product.ProductMonitorConvert;
import com.wmh.baseservice.operationaid.entity.ProductMonitor;
import com.wmh.baseservice.operationaid.mapper.ProductMonitorMapper;
import com.wmh.baseservice.operationaid.pojo.vo.product.monitor.ProductMonitorCreateReqVO;
import com.wmh.baseservice.operationaid.pojo.vo.product.monitor.ProductMonitorUpdateReqVO;
import com.wmh.baseservice.operationaid.service.ProductMonitorService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 谢骏
 * @description 针对表【operation_aid_product_monitor】的数据库操作Service实现
 * @createDate 2023-09-25 11:45:58
 */
@Service
public class ProductMonitorServiceImpl extends ServiceImpl<ProductMonitorMapper, ProductMonitor>
        implements ProductMonitorService {

    @Resource
    private UserUtil userUtil;

    @Override
    public Long create(ProductMonitorCreateReqVO reqVO) {
        checkProductIdExist(null, reqVO.getProductId());
        ProductMonitor entity = ProductMonitorConvert.INSTANCE.convert(reqVO, userUtil.getId());
        baseMapper.insert(entity);
        return entity.getId();
    }

    @Override
    public void delete(List<Long> ids) {
        baseMapper.deleteBatchIds(ids);
    }

    @Override
    public Long update(ProductMonitorUpdateReqVO reqVO) {
        checkNotExist(reqVO.getId());
        ProductMonitor entity = ProductMonitorConvert.INSTANCE.convert(reqVO, userUtil.getId());
        baseMapper.updateById(entity);
        return entity.getId();
    }


    private void checkNotExist(Long id) {
        ProductMonitor productMonitor = baseMapper.selectById(id);
        if (productMonitor == null) {
            throw new ServiceException("操作数据已不存在");
        }
    }

    private void checkProductIdExist(Long adId, Long productId) {
        ProductMonitor productMonitor = baseMapper.selectOne(new LambdaQueryWrapperX<ProductMonitor>()
                .eq(ProductMonitor::getProductId, productId)
                .neIfPresent(ProductMonitor::getAdId, adId));
        if (productMonitor != null) {
            throw new ServiceException("该商品编号被您或其他人添加");
        }
    }
}




